//
//  WBComposeViewController.swift
//  SinaWeibo
//
//  Created by 风不会停息 on 2016/11/21.
//  Copyright © 2016年 风不会停息. All rights reserved.
//

import UIKit

import SVProgressHUD

class WBComposeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.white
        
        registerNotification()
        setNav()
        setTextView()
        setPicSelector()
        settoolBar()
        
        // Do any additional setup after loading the view.
    }

    //注册键盘监听的通知
    private func registerNotification(){
        
        //注册键盘frame变化的通知
        NotificationCenter.default.addObserver(self, selector:#selector(keyboardChanged(n:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
        
        //注册表情选择通知
        NotificationCenter.default.addObserver(self, selector: #selector(insertEmoticon(n:)), name: NSNotification.Name(KSelectEmoticon), object: nil)
        
    }
    
    @objc private func insertEmoticon(n:Notification){

        
        guard let em = n.object as? HMEmoticon else{
            
            //点击删除按钮
            textView.deleteBackward()
            return
        }
//        let em = n.object as? HMEmoticon
//        textView.inputEmoticon(emoticon: em)
        // inputEmoticon的实现原理
        if em.type == 1{
            //将emoji表情插入到光标选择的位置
            textView.replace(textView.selectedTextRange!, withText: em.emojiStr ?? "")
            return
        }
        //在经过之前的筛选，程序走到这里，一定是图片表情
        
        
    //2、通过附件对象实例化属性字符串
        
        
        
        //1.实例化附件对象，将图片包装到附件对象中  attachment
        let attach = HMTextAttachment()
        
        attach.chs = em.chs
        let lineHeight = textView.font!.lineHeight
        
        
        //如果不设置，插入的图片表情后面，大小会是默认
        attach.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
        
        //bundle是存放程序资源路径的包，使用bundle实现同名的图片不同路径进行加载
        attach.image = UIImage(named: em.imagePath!, in: HMEmoticonTools.sharedEmoticonTools.emoticonBundle, compatibleWith: nil)
        //2.通过附件对象实例化一个 可变的属性字符串（后面要添加属性）imageText
        
        let imageText = NSMutableAttributedString(attributedString: NSAttributedString(attachment: attach))
        
        //需要给附件文本添加属性
        imageText.addAttributes([NSFontAttributeName:textView.font!], range: NSRange(location: 0, length: 1))
        //3.获取当前文本输入视图可变的属性字符串 strM
        let strM = NSMutableAttributedString(attributedString: textView.attributedText)
        
        //3.1 在替换属性文本 之前 线记录光标选中的位置
        let range = textView.selectedRange
        
        //4.将imageText替换到光标位置
        strM.replaceCharacters(in: textView.selectedRange, with: imageText)
        //5.将strM赋给textView的attributeText的属性上
        textView.attributedText = strM
        
        
        //6. 将光标恢复到之前选中的位置
        textView.selectedRange = NSRange(location: range.location + 1, length: 0)
        
        //调用textdidchange的代理方法
        textView.delegate?.textViewDidChange?(textView)
        
    }
    
    
    @objc private func keyboardChanged(n: Notification) {
        
        let endframe = n.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
        
        
        let offsetY = -(ScreenHeight - endframe.origin.y)

       
        UIView.animate(withDuration: 0.25, animations: {
            
            
            self.toolBar.snp.updateConstraints({ (make) in
                make.bottom.equalTo(self.view).offset(offsetY)
            })
            self.view.layoutIfNeeded()
         
            
        })
        
    }
    
    @objc internal func close(){
//        self.view.alpha = 0
        self.textView.endEditing(true)
        dismiss(animated: true, completion: nil)
    }
    //懒加载发送按钮
    lazy var sendBtn: UIBarButtonItem = {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 60, height: 35))
        //设置文字
        btn.setTitle("发送", for: .normal)
        //设置背景图片
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange"), for: .normal)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(#imageLiteral(resourceName: "common_button_white_disable"), for: .disabled)
        btn.setTitleColor(UIColor.darkGray, for: .disabled)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.addTarget(self, action: #selector(sendBtnDidClick), for: .touchUpInside)
        //设置文字颜色
        let barButtonItem = UIBarButtonItem(customView: btn)
        barButtonItem.isEnabled = false
        return barButtonItem
    }()
    //懒加载textView
    lazy var textView:UITextView = {
        let txtView = UITextView()
        txtView.font = UIFont.systemFont(ofSize: 18)
        txtView.textColor = UIColor.darkGray
        //textView 没有占位文本
//        txtView.text = "我是小王"
        //tv.backgroundColor = randomColor()
        txtView.keyboardDismissMode = .onDrag
        txtView.alwaysBounceVertical = true
        txtView.delegate = self
        return txtView
    }()
    //懒加载textVIew的占位符
    lazy var placeHolderLabel: UILabel = {
        let l = UILabel(title: "无聊就发条微博吧", fontSize: 18, textcolor: UIColor.darkGray)
        return l
    }()
    //懒加载toolbar
    lazy var toolBar:UIStackView = {
        let toolBar = UIStackView(frame: CGRect.zero)
        //初始设置
//        toolBar.backgroundColor = UIColor.purple
        //设置方向
        toolBar.axis = .horizontal
        //设置填充方式
        toolBar.distribution = .fillEqually
        return toolBar
    }()
    //懒加载图片选择控制器
    lazy var pictureChooseVC:WBPictureSelectorController = {
       
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: selectorCellWidth, height: selectorCellWidth)
        flowLayout.minimumLineSpacing = selectorMargin
        flowLayout.minimumInteritemSpacing = selectorMargin
        
        //组内间距的设置
        flowLayout.sectionInset = UIEdgeInsets(top: selectorMargin, left: selectorMargin, bottom: 0, right: selectorMargin)
        
        let picvc = WBPictureSelectorController(collectionViewLayout: flowLayout)
        
        picvc.collectionView?.backgroundColor = UIColor.white
//        picvc.view.backgroundColor = UIColor.red

        return picvc
    }()
    //懒加载textView的自定义的inputVIew（将emoji键盘加到textview中）
    lazy var keyboardView:HMEmoticonKeyboardView = HMEmoticonKeyboardView(frame: CGRect(x: 0, y: 0, width: 0, height: 220))
    

    
    @objc private func sendBtnDidClick() {
        
//        
//        print(textView.text)
//        
//        print("--------------")
//        
//        print(textView.attributedText)
        
        
        //本段代码封装到了textVIew.imageEmoticon2Chs中，返回一个字符串作为请求参数发送给服务器
//        var strM = String()
//        
//        //如果属性文本中包含图片，属性中就会包含nsattachment的，这个key一定会对应一个附件对象
//        textView.attributedText.enumerateAttributes(in: NSMakeRange(0, textView.attributedText.length), options: [], using: {(dict,range,_) -> () in
//            
//            if let attachment = dict["NSAttachment"] as? HMTextAttachment{
//                
//                
//                print(attachment.chs)
//                strM += attachment.chs ?? ""
//                
//            }else {
//                
//                let sub = (textView.text as NSString).substring(with: range)
//                
//                strM += sub
//            }
//            
//            
//        })
        
        
        
        
        
        var urlString = "https://api.weibo.com/2/statuses/update.json"
        
        //需要将文字调用imageEmoticon2CHs方法才能发送给服务器
        let parameter = ["access_token":WBUserAccountViewModel.WBUserAccountShared.access_token,"status":textView.imageEmoticon2Chs()]
        
        
//        let parameter = ["access_token":WBUserAccountViewModel.WBUserAccountShared.access_token,"status":strM]

        if pictureChooseVC.selectedImage.count == 0 {
        WBNetWorkTools.tool.request(method: .POST, urlString: urlString, parameter: parameter, finished: { (responseObject,error) -> () in
            if error != nil {
                SVProgressHUD.showError(withStatus: "发布微博失败")
                return
            }
            
            SVProgressHUD.showSuccess(withStatus: "发布微博成功")
            self.close()
        })
        }else {
            urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
             let imageData = UIImagePNGRepresentation(self.pictureChooseVC.selectedImage.first!)
            
            WBNetWorkTools.tool.post(urlString, parameters: parameter, constructingBodyWith: { (formdata) in
                //将需要上传的文件的二进制数据拼接到formdata中
                //withFileData: 需要上传的文件的二进制数据
                //name: 服务器接收的字段 "pic"
                //fileName: 服务器存储的名称, 不过新浪微博的服务器会对用户上传的图片按照自己的规则进行处理
                //mimeType: 标识文件类型
                formdata.appendPart(withFileData: imageData!, name: "pic", fileName: "xxxxx", mimeType: "application/octet-stream")
            }, progress: nil, success: { (_, result) in
                SVProgressHUD.showSuccess(withStatus: "发布微博成功")
                self.close()
            }, failure: { (_, error) in
                print(error)
                SVProgressHUD.showError(withStatus: "发布图片微博失败")
            })
        }
        
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    


}
extension WBComposeViewController{
    internal func setNav(){
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .plain, target: self, action: #selector(close))
        self.navigationItem.rightBarButtonItem = sendBtn
        
        let titleLabel = UILabel()
        titleLabel.textAlignment = .center
        titleLabel.numberOfLines = 0
        if let userName = WBUserAccountViewModel.WBUserAccountShared.account?.name{
            let titleText = "发布微博\n\(userName)"
            titleLabel.text = titleText
            //改变局部文字的颜色属性
            //改变属性文本的属性，使用可变的属性文本（添加属性），不可变的属性文本是不能添加属性的
            let strM = NSMutableAttributedString(string: titleText)
            
            let range = (titleText as NSString).range(of: userName)
            
            strM.addAttributes([NSFontAttributeName:UIFont.systemFont(ofSize: 13),NSForegroundColorAttributeName:UIColor.orange], range: range)
            titleLabel.attributedText = strM
            
        }else{
            titleLabel.text = "发布微博"
        }
        titleLabel.sizeToFit()
        self.navigationItem.titleView = titleLabel
    }

        //设置textView
        func setTextView() {
            //添加子视图
            self.view.addSubview(textView)
            //添加占位文本
            self.textView.addSubview(placeHolderLabel)
            
            placeHolderLabel.isHidden = textView.hasText
//            textView.becomeFirstResponder()
            
            //实例化textView控件 添加约束
            textView.snp.makeConstraints { (make) in
                make.top.left.right.equalTo(self.view)
                //添加高度约束
                make.height.equalTo(ScreenHeight / 3)
            }
            
            placeHolderLabel.snp.makeConstraints { (make) in
                make.top.equalTo(textView).offset(8)
                make.left.equalTo(textView).offset(5)
            }
            
            //设置占位文本的约束
        }
    func settoolBar(){
        
        self.view.addSubview(toolBar)
        
        toolBar.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(40)
        }
        toolBar.backgroundColor = UIColor.white
        let imageNames = ["compose_toolbar_picture",
                          "compose_mentionbutton_background",
                          "compose_trendbutton_background",
                          "compose_emoticonbutton_background",
                          "compose_add_background"]
        for (index,imageName) in imageNames.enumerated() {
            
            let btn = UIButton()
            
            btn.setImage(UIImage(named:imageName), for: .normal)
//            btn.setTitleColor(UIColor.init(white: 0.9, alpha: 1), for: .normal)
            btn.backgroundColor = UIColor(white: 0.9, alpha: 1)
            btn.sizeToFit()
            
            toolBar.addArrangedSubview(btn)
            
            btn.addTarget(self, action: #selector(toolBarBtnClick(btn:)), for: .touchUpInside)
            btn.tag = index
        }
        
    }
    
    func setPicSelector(){
        
        
        self.addChildViewController(pictureChooseVC)
        self.view.addSubview(pictureChooseVC.view)
        
        pictureChooseVC.view.snp.makeConstraints { (make) in
            make.left.bottom.right.equalTo(self.view)
            make.height.equalTo(ScreenHeight / 3 * 2)
        }
        
    }
    
    @objc private func toolBarBtnClick(btn:UIButton){
        switch btn.tag {
        case 0:
            print("选择图片")
            pictureChooseVC.userWillChoose(cell: nil)
        case 1:
            print("@某人")
        case 2:
            print("话题")
        case 3:
            print("选择表情")
            textView.inputView = textView.inputView == nil ? keyboardView : nil
            if !textView.isFirstResponder {
                textView.becomeFirstResponder()
            }
            
            //刷新输入视图
            textView.reloadInputViews()
            
        case 4:
            print("更多")
        default: break
            
        }
    }

    }

extension WBComposeViewController:UITextViewDelegate{
    func textViewDidChange(_ textView: UITextView) {
        
        //代理方法的作用是在文字改变的时候根据textView是否有文字来决定发送按钮是否可用
        //还有决定的是占位label的隐藏
        sendBtn.isEnabled = textView.hasText
        placeHolderLabel.isHidden = textView.hasText
//        textView.keyboardDismissMode = .onDrag
    }
    
}
